package com.podmanager.data;

import java.net.URI;
import java.util.GregorianCalendar;

import com.podmanager.RssFeed.RSSParser;
import com.podmanager.UI.*;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/*
 * Downloads the podcast (audio) file to its respective directory 
 * (currently, /mnt/sdcard/podmanager/podcasts/)
 */
public class DownloadPodcastAsyncTask extends AsyncTask<String, Void, Cursor> {
	private Context context;
	private String url;
	private String fileName;
	private Notification mNotification;
	private String title;
	private NotificationManager mNotificationManager;
	private int NOTIFICATION_ID=(int) GregorianCalendar.getInstance().getTimeInMillis();
	
	public DownloadPodcastAsyncTask(Context context, String title) {
		super();
		this.context = context;
		this.title=title;
	}

    @SuppressWarnings("deprecation")
	@Override
    protected void onPreExecute() {

        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //create the notification
        PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(), 0);
		mNotification = new Notification();
		mNotification.tickerText = "Downloading: "+title;
		mNotification.icon = R.drawable.ic_launcher;
		mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
		mNotification.setLatestEventInfo(context, "Podmanager is Downloading:",title, pi);
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }
    
	@Override
	protected Cursor doInBackground(String... params) {
		long id = Long.parseLong(params[0]);
		
		Cursor c = context.getContentResolver().query(DBContentProvider.EPISODES_URI, 
				new String [] {PMDatabase.EPISODES.FILE_URL, PMDatabase.EPISODES.FILE_PATH}, 
				PMDatabase.EPISODES.KEY_ROW_ID + "=" + id, null, null);

		c.moveToFirst();
		url = c.getString(0);
		Log.d("_id = ", url);
		fileName = c.getString(1);
		Log.d("fileName = ", fileName);

		RSSParser download = new RSSParser(url, fileName);
		download.downloadRSS();
		updateDownloadedEpisodes(id);
		
		return c;
	}
	
	private void updateDownloadedEpisodes(long id) {
		try {
			Cursor c = context.getContentResolver().query(DBContentProvider.EPISODES_URI, 
															new String[] {PMDatabase.EPISODES.SUB_ROW_ID}, 
															PMDatabase.EPISODES.KEY_ROW_ID + "=" + id, null, null);
			c.moveToFirst();
			long subscription_id = c.getLong(0);
			c.close();
			
			c = context.getContentResolver().query(DBContentProvider.SUBSCRIPTION_URI, 
					new String[] {PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED}, 
					PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID + "=" + subscription_id, null, null);
			c.moveToFirst();
			long episodes_downloaded = c.getLong(0);
			c.close();
			episodes_downloaded++;
			
			String filter = PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID + "=" + subscription_id;
			ContentValues args = new ContentValues();
			args.put(PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED, episodes_downloaded);

			int rows = context.getContentResolver().update(DBContentProvider.SUBSCRIPTION_EPI_DOWNLOADED_URI, 
					args, filter, null);

			
			System.out.println("updated downloaded episode row " + rows);
		} catch (Exception e) 
		{ 
			e.printStackTrace();
		}
		
	}

	@SuppressWarnings("deprecation")
	@Override
    protected void onPostExecute(Cursor c) {
		if (c == null)
		{
			Toast.makeText(context, "error downloading podcast.  Try again", Toast.LENGTH_LONG).show();
			Log.i("download", "error downloading podcast.  Try again");
		}
		else
		{
			Toast.makeText(context, "Download Podcast Complete", Toast.LENGTH_LONG).show();
			Log.i("download", "Download Podcast Complete");
			c.close();  // I don't think this was getting closed..
		}
        PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(), 0);
		mNotification = new Notification();
		mNotification.tickerText = "Download Complete";
		mNotification.icon = R.drawable.ic_launcher;
		mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		mNotification.setLatestEventInfo(context, "Finished Downloading",title, pi);
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
        
        
    }
}
